//
//  NSString+category.m
//  IAPDemo
//
//  Created by Charles.Yao on 2016/10/31.
//  Copyright © 2016年 com.pico. All rights reserved.
//

#import "NSString+category.h"

@implementation NSString (category)

+ (NSString *)uuid{
    // create a new UUID which you own
    CFUUIDRef uuidref = CFUUIDCreate(kCFAllocatorDefault);
    
    // create a new CFStringRef (toll-free bridged to NSString)
    // that you own
    CFStringRef uuid = CFUUIDCreateString(kCFAllocatorDefault, uuidref);
    
    NSString *result = (__bridge NSString *)uuid;
    //release the uuidref
    CFRelease(uuidref);
    // release the UUID
    CFRelease(uuid);
    
    return result;
}

+ (NSString *)urlSignImage:(NSString *)url {
    NSString *avatar=url;
    NSDictionary *saveOpen_app_config = [Config getOpenAppConfig];
    NSString *cos_url=@"";
    NSString *cos_auth=@"";
    NSString *urlSuffix=@"";
    if (saveOpen_app_config!=nil) {
        cos_url=saveOpen_app_config[@"cos_url"];
        NSLog(@"%@",cos_url);//https://cos.nnyc123.cn
        
        cos_auth=saveOpen_app_config[@"cos_auth"];
        NSLog(@"%@",cos_auth);//ssM7AOlb5Xio2015kLKmayc
        urlSuffix = [avatar substringFromIndex:cos_url.length];
        NSLog(@"%@",urlSuffix);//common/app/male.png
        
        NSString *timeStamp=[AES128 getNowTimeStamp];//1744628907
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        NSString *str=[NSString stringWithFormat:@"MineHeadtimeStamp%@",[Config getID]];
        NSString *t=[userDefaults objectForKey:str];
        if (t!=nil&&![t isEqualToString:@""]) {
            timeStamp=t;
        }else{
            [userDefaults setObject:timeStamp forKey:str];
            [userDefaults synchronize];
        }
        NSString *urlStr=[NSString stringWithFormat:@"%@%@%@",cos_auth,urlSuffix,timeStamp];
        NSLog(@"%@",urlStr);//ssM7AOlb5Xio2015kLKmayc/common/app/male.png1744628907
        NSData *data = [urlStr dataUsingEncoding:NSUTF8StringEncoding];
        
        if (data) {
            // 转换成功，data 包含了UTF-8编码的字节数组
            // 例如，你可以将NSData写入文件或通过网络发送
            NSLog(@"转换成功");
            
            NSData *md5Result = [AES128 dataWithMD5Hash:data];
            NSString *hexString = [AES128 hexStringFromData:md5Result];
            
            NSString *url=[NSString stringWithFormat:@"%@?sign=%@&t=%@",avatar,hexString,timeStamp];
            return url;
        } else {
            // 转换失败
            NSLog(@"Failed to convert string to NSData.");
        }
    }
    
    return nil;
}

@end
